//
//  RSSpecialField.m
//  RSTools
//
//  Created by thinkjoy on 2017/10/10.
//  Copyright © 2017年 杜瑞胜. All rights reserved.
//

#import "RSSpecialField.h"

@interface RSSpecialField()<UIKeyInput>

@property   (nonatomic,strong)  NSMutableArray  * numberLabMuAry;


@end

#define SpaceBetweenDigits  (10.f)  //默认间距

//修改属性后，是否在XIB上动态显示
//IB_DESIGNABLE

@implementation RSSpecialField

@synthesize textColor   =   _textColor;
@synthesize textBackColor    =  _textBackColor;
@synthesize dashColor    =  _dashColor;
@synthesize dashBackColor    =  _dashBackColor;

#pragma mark    - init
- (instancetype)init __attribute__((deprecated))
{
    self    =   [super init];
    [self initDefaultData];
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self    =   [super initWithFrame:frame];
    [self initDefaultData];
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self    =   [super initWithCoder:aDecoder];
    [self initDefaultData];
    return self;
}
- (void)initDefaultData
{
    _numberOfDigits =   4;
    
//    _textColor  =   [UIColor blackColor];
//    _textBackColor  =   [UIColor yellowColor];
//
//    _dashColor  =   [UIColor grayColor];
//    _dashBackColor  =   [UIColor greenColor];
    
    _spaceBetweenDigits =   SpaceBetweenDigits;
    _enableEmptyDash    =   YES;
    [self setup];
}
#pragma mark    - set
- (void)setNumberOfDigits:(NSInteger)numberOfDigits
{
    if (_numberOfDigits!=numberOfDigits) {
        _numberOfDigits =   numberOfDigits;
        
        [self dynamicRelayout];
        [self redisplay];
    }
}
- (void)setInputNumberStr:(NSString *)inputNumberStr
{
    if ([self isNumberStr:inputNumberStr] && ![_inputNumberStr isEqualToString:inputNumberStr]) {
        _inputNumberStr  =   inputNumberStr;
        
        [self redisplay];
        [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
}

- (void)setSecureTextEntry:(BOOL)secureTextEntry
{
    if (_secureTextEntry != secureTextEntry) {
        _secureTextEntry  =   secureTextEntry;
        
        [self dynamicRelayout];
        [self redisplay];
    }
}

- (void)setEnableEmptyDash:(BOOL)enableEmptyDash
{
    if (_enableEmptyDash != enableEmptyDash) {
        _enableEmptyDash    =   enableEmptyDash;
        
        [self dynamicRelayout];
        [self redisplay];
    }
}

- (void)setSpaceBetweenDigits:(CGFloat)spaceBetweenDigits
{
    if (_spaceBetweenDigits!=spaceBetweenDigits) {
        if (spaceBetweenDigits<0) {
            if (_spaceBetweenDigits==SpaceBetweenDigits) {
                return;
            }
            _spaceBetweenDigits =   SpaceBetweenDigits;
        }
        _spaceBetweenDigits =   spaceBetweenDigits;
        
        [self dynamicRelayout];
        [self redisplay];
    }
}

- (void)setTextColor:(UIColor *)textColor
{
    if (![_textColor isEqual:textColor]) {
        _textColor  =   textColor;
        [self redisplay];
    }
}

- (void)setTextBackColor:(UIColor *)textBackColor
{
    if (![_textBackColor isEqual:textBackColor]) {
        _textBackColor  =   textBackColor;
        [self redisplay];
    }
}

- (void)setDashColor:(UIColor *)dashColor
{
    if (![_dashColor isEqual:dashColor]) {
        _dashColor  =   dashColor;
        [self redisplay];
    }
}

- (void)setDashBackColor:(UIColor *)dashBackColor
{
    if (![_dashBackColor isEqual:dashBackColor]) {
        _dashBackColor  =   dashBackColor;
        [self redisplay];
    }
}
#pragma mark    - get
- (UIColor*)textColor{
    if (_textColor==nil) {
        _textColor  =   [UIColor blackColor];
    }
    return _textColor;
}
- (UIColor*)textBackColor{
    if (_textBackColor==nil) {
        _textBackColor  =   [UIColor yellowColor];
    }
    return _textBackColor;
}
- (UIColor*)dashColor{
    if (_dashColor==nil) {
        _dashColor  =   [UIColor grayColor];
    }
    return _dashColor;
}
- (UIColor*)dashBackColor{
    if (_dashBackColor==nil) {
        _dashBackColor  =   [UIColor greenColor];
    }
    return _dashBackColor;
}
#pragma mark    -
- (void)setup{
    [self addTarget:self action:@selector(didTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self dynamicRelayout];
    [self redisplay];
}

//动态重布局
- (void)dynamicRelayout
{
    [self.numberLabMuAry enumerateObjectsUsingBlock:^(UILabel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    
    [self.numberLabMuAry removeAllObjects];
    
    for (int i=0; i<_numberOfDigits; i++) {
        UILabel * lab   =   [UILabel new];
        lab.text    =   @"";
        lab.textAlignment   =   NSTextAlignmentCenter;
        [self.numberLabMuAry addObject:lab];
        [self addSubview:lab];
    }
    [self setNeedsLayout];
}

- (void)redisplay
{
    for (int i=0; i<self.numberLabMuAry.count; i++) {
        UILabel * lab   =   self.numberLabMuAry[i];
        if (i<_inputNumberStr.length) {
            lab.text    =   _secureTextEntry?@"＊":[_inputNumberStr substringWithRange:NSMakeRange(i, 1)];
            lab.textColor   =   self.textColor;
            lab.backgroundColor =   self.textBackColor;
        }else{
            lab.text    =   _enableEmptyDash?@"-":@"";
            lab.textColor   =   self.dashColor;
            lab.backgroundColor =   self.dashBackColor;
        }
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    for (int i=0; i<self.numberLabMuAry.count; i++) {
        UILabel * lab   =   self.numberLabMuAry[i];
        CGRect   frame   =   [self frameOfNumberLabelOfDigitIndex:i];
        lab.font    =   [UIFont systemFontOfSize:frame.size.width*0.9];
        lab.frame   =   frame;
    }
    
}
- (CGRect)frameOfNumberLabelOfDigitIndex:(int)index
{
    CGFloat w   =   (self.frame.size.width - _spaceBetweenDigits * (_numberOfDigits-1))/_numberOfDigits;
    CGFloat h   =   self.frame.size.height;
    CGFloat x   =   (w + _spaceBetweenDigits) * index;
    CGFloat y   =   0;
    return CGRectMake(x, y, w, h);
}

#pragma mark    - UIKeyInput protocol
- (BOOL)hasText
{
    if (_inputNumberStr.length<1 || [_inputNumberStr isEqualToString:@""] || [_inputNumberStr isEqual:NULL]) {
        return NO;
    }
    return YES;
}

- (void)insertText:(NSString *)text
{
    if (_inputNumberStr.length+text.length>_numberOfDigits || ![self isNumberStr:text]) {
        return;
    }
    if (_inputNumberStr.length) {
        self.inputNumberStr  =   [NSString stringWithFormat:@"%@%@",_inputNumberStr,text];
    }else{
        self.inputNumberStr  =   text;
    }
    if (self.inputNumberHadChange) {
        self.inputNumberHadChange(self.inputNumberStr);
    }
}

- (void)deleteBackward
{
    if (_inputNumberStr.length<1) {
        return;
    }
    
    if (_inputNumberStr.length>_numberOfDigits) {
        self.inputNumberStr  =   [_inputNumberStr substringToIndex:_numberOfDigits-1];
    }else{
        self.inputNumberStr  =   [_inputNumberStr substringToIndex:_inputNumberStr.length-1];
    }
    if (self.inputNumberHadChange) {
        self.inputNumberHadChange(self.inputNumberStr);
    }
}

#pragma mark    - lazy
- (NSMutableArray *)numberLabMuAry
{
    if (_numberLabMuAry==nil) {
        _numberLabMuAry =   [NSMutableArray array];
    }
    return _numberLabMuAry;
}

#pragma mark - isNumberStr
- (BOOL)isNumberStr:(NSString *)numberStr
{
    NSString * CM = @"^[0-9]*$";
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    if ([regextestcm evaluateWithObject:numberStr]) {
        return YES;
    }
    return NO;
}

#pragma mark    - Handle the touch up event
- (void)didTouchUpInside
{
    [self becomeFirstResponder];
}
#pragma mark    UIResponder
- (BOOL)canBecomeFirstResponder
{
    return YES;
}
#pragma mark    UIKeyboardTrait
- (UIKeyboardType)keyboardType
{
    return UIKeyboardTypeNumberPad;
}
@end


